﻿using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.InvDoc;
using dz.u9.jky.schema.PM;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.CBO.SCM.Bin;
using UFIDA.U9.ISV.PM;
using UFIDA.U9.ISV.TransferInISV;
using UFSoft.UBF.Business;
using UFSoft.UBF.Transactions;

namespace dz.inner.jky.api.service
{
    internal class TransferInService : BaseService
    {
        public U9CResult Add(DzTransferIn dto)
        {
            return util.U9Invoke(__Add, dto, dto.Org);
        }

        public void Submit(CommonDoc doc)
        {
            TransferInBatchCommitSRV srv = new TransferInBatchCommitSRV();

            CommonArchiveDataDTO dto = new CommonArchiveDataDTO() { Code=doc.DocNo,ID = doc.ID};

            srv.DocList = new List<CommonArchiveDataDTO>() {dto};

            srv.Do(); 
        }

        public void Audit(CommonDoc doc)
        {
            TransferInBatchApproveSRV srv = new TransferInBatchApproveSRV();

            CommonArchiveDataDTO dto = new CommonArchiveDataDTO() { Code = doc.DocNo, ID = doc.ID };

            srv.DocList = new List<CommonArchiveDataDTO>() { dto };

            srv.Do();
        }

        #region 私有函数
        private U9CResult __Add(DzTransferIn dto)
        {
            U9CResult result = new U9CResult();

            CommonCreateTransferInSV sv = new CommonCreateTransferInSV();

            sv.TransferInDTOList = Convert(dto);

            var rtn = sv.Do();

            result.DocNo = rtn[0].Code;
            result.Id = rtn[0].ID;
            result.IsSuccess = true;

   

            return result;

        }

        private List<IC_TransferInDTO> Convert(DzTransferIn entity)
        {
            IC_TransferInDTO dto = new IC_TransferInDTO();

            ObjectCopyUtil util = new ObjectCopyUtil();

            util.CopyProperty(entity, ref dto);

            string where = $"code = '{dto.Org.Code}'";
            long org = Organization.Finder.Find(where).ID;

            if (dto.TransInLines != null && dto.TransInLines.Count > 0)
            {
                foreach (IC_TransInLineDTO line in dto.TransInLines)
                {
                    foreach (var bin in line.TransInBins)
                    {
                        bin.BinInfo.Bin = Bin.Finder.Find($"code = '{bin.BinInfo.Bin.Code}' and org = {org}");
                        if (bin.BinInfo.Bin == null)
                        {
                            throw new Exception($"组织{entity.Org}中 找不到库位：{bin.BinInfo.Bin.Code}");
                        }
                    }
                }
            }


            List<IC_TransferInDTO> rtn = new List<IC_TransferInDTO>() { dto };

            return rtn;
        }
        #endregion
    }
}
